'use strict';
const db = uniCloud.database()
const coursesCollection = db.collection('courses')

exports.main = async (event, context) => {
	const { page = 1, pageSize = 10, keyword = '', categoryId = '' } = event
	
	try {
		// 构建查询条件
		const query = {}
		if (keyword) {
			// 使用正则表达式进行模糊搜索
			const regex = new RegExp(keyword, 'i')
			query.title = regex
		}
		
		// 添加分类筛选条件
		if (categoryId) {
			query.categoryId = categoryId
		}
		
		// 获取总记录数
		const total = await coursesCollection.where(query).count()
		
		// 获取分页数据
		const list = await coursesCollection
			.where(query)
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.orderBy('createTime', 'desc')
			.get()
		
		return {
			code: 0,
			msg: '获取成功',
			data: {
				list: list.data,
				total: total.total,
				page,
				pageSize,
				hasMore: list.data.length === pageSize
			}
		}
	} catch (e) {
		return {
			code: -1,
			msg: '获取失败',
			error: e
		}
	}
} 